package apps.sim.core.log;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Console {
	public static enum Color {
		ERROR("red"), WARNING("yellow"), INFO("#45BF55");
		private String color;

		private Color(String color) {
			this.color = color;
		}
	}

	private static final List<String> logs = new ArrayList<String>();
	private static final Map<String, OutputStream> streams = new HashMap<String, OutputStream>();

	public static void addStream(String name, OutputStream stream) {
		streams.put(name, stream);
	}

	public static OutputStream getStream(String name) {
		return streams.get(name);
	}

	public static void printOnly(String message, Color color) {
		logs.add("<p style=\"color:" + color.color + "\">$$> " + message + "</p>");
		printInStreams(message);
		flush();
	}

	public static void printInfo(String message) {
		print(message, Color.INFO);
	}

	public static void print(String message, Color color) {
		printOnly(message, color);
		Logger.log(message);
	}

	private static void printInStreams(String message) {
		final Collection<OutputStream> values = streams.values();
		for (OutputStream stream : values) {
			try {
				stream.write(message.getBytes());
				stream.write("\n".getBytes());
				stream.flush();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}

	private static synchronized void flush() {
		if (logs.size() > 1000) {
			final List<String> subList = logs.subList(1000, logs.size() - 1);
			logs.remove(subList);
		}
	}

	public static synchronized String getLogs() {
		final StringBuilder builder = new StringBuilder();
		builder.append("<logs>");
		if (logs.size() > 0) {
			builder.append("<log>");
			builder.append("<![CDATA[");
			builder.append(logs.remove(0));
			builder.append("]]>");
			builder.append("</log>");
		}
		builder.append("</logs>");
		return builder.toString();
	}

}
